import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { City } from 'src/app/shared/interfaces/city.interface';
import { CarwashesService } from 'src/app/shared/services/http/carwashes.service';
import { CarwashDto } from 'src/app/shared/services/http/dto/carwash.dto';
import { NzMessageService } from 'ng-zorro-antd/message';

@Component({
  selector: 'app-edit-carwash-form',
  templateUrl: './edit-carwash-form.component.html',
  styleUrls: ['./edit-carwash-form.component.css'],
})
export class EditCarwashFormComponent implements OnInit {
  // 洗车点表单
  carwashForm: FormGroup = this.formBuilder.group({
    name: [''],
    city: [[]],
    address: [''],
    longitude: [''],
    latitude: [''],
    price: [''],
    state: [''],
  });

  // 地区数据
  nzOptions: City[] | null = null;

  // 级联选择值
  values: string[] | null = null;

  // 按钮是否被禁止
  disabled = false;

  // 要编辑的洗车点
  // tslint:disable-next-line: variable-name
  private _carwash: CarwashDto;

  // _id
  // tslint:disable-next-line: variable-name
  _id = '';

  // 更新成功事件
  @Output() update = new EventEmitter();

  @Input()
  set carwash(carwash: CarwashDto) {
    this._carwash = carwash;

    if (carwash) {
      const {
        _id,
        name,
        city,
        address,
        longitude,
        latitude,
        price,
        state,
      } = carwash;
      this._id = _id;
      this.carwashForm = this.formBuilder.group({
        name: [name],
        city: [city],
        address: [address],
        longitude: [longitude],
        latitude: [latitude],
        price: [price],
        state: [state.toString()],
      });
    }
  }

  get carwash() {
    return this._carwash;
  }

  constructor(
    private formBuilder: FormBuilder,
    private carwashesService: CarwashesService,
    private message: NzMessageService,
  ) {}

  ngOnInit(): void {
    // 获取城市级联数据
    this.carwashesService.getCitiesOptions().subscribe((value) => {
      this.nzOptions = value;
    });
  }

  /**
   * 提交编辑洗车点
   * @param carwashDto 洗车点
   */
  onSubmit(carwashDto: CarwashDto) {
    this.disabled = true;
    this.carwashesService.updateById(this._id, carwashDto).subscribe(() => {
      this.message.create('success', `修改洗车点成功`);
      this.disabled = false;
      this.update.emit();
    });
  }
}
